package com.example.computewindowsizeclasses;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.window.core.layout.WindowHeightSizeClass;
import androidx.window.core.layout.WindowSizeClass;
import androidx.window.core.layout.WindowWidthSizeClass;
import androidx.window.layout.WindowMetrics;
import androidx.window.layout.WindowMetricsCalculator;

/**
 * 使用窗口大小类别
 * https://developer.android.google.cn/develop/ui/views/layout/use-window-size-classes?hl=zh-cn#java
 *
 * 包含 View 的响应式/自适应设计
 * https://developer.android.google.cn/develop/ui/views/layout/responsive-adaptive-design-with-views?hl=zh-cn
 */
public class MainActivity extends ComponentActivity {
    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);
        ViewGroup container = findViewById(R.id.fl);

        container.addView(new View(this) {
            @Override
            protected void onConfigurationChanged(Configuration newConfig) {
                super.onConfigurationChanged(newConfig);
                computeWindowSizeClasses();
            }
        });

        computeWindowSizeClasses();
    }

    private void computeWindowSizeClasses() {
        WindowMetrics metrics = WindowMetricsCalculator.getOrCreate()
                .computeCurrentWindowMetrics(this);

        int width = metrics.getBounds().width();
        int height = metrics.getBounds().height();
        float density = getResources().getDisplayMetrics().density;

        WindowSizeClass windowSizeClass = WindowSizeClass.compute(width / density, height / density);
        // COMPACT, MEDIUM, or EXPANDED
        WindowWidthSizeClass widthWindowSizeClass = windowSizeClass.getWindowWidthSizeClass();
        // COMPACT, MEDIUM, or EXPANDED
        WindowHeightSizeClass heightWindowSizeClass = windowSizeClass.getWindowHeightSizeClass();

        // Use widthWindowSizeClass and heightWindowSizeClass.
        // figma 标注 宽
        // 1/3  w = 980
        // 2/3  w = 1570
        // 1    w = 2560
        // 当前实际 宽，容器正在修改
        // 1/3  w = 848
        // 2/3  w = 1697
        // 1    w = 2560
        Log.i(TAG, "width : " + width);
        Log.i(TAG, "height : " + height);
        Log.i(TAG, "density : " + density);
        Log.i(TAG, "widthWindowSizeClass : " + widthWindowSizeClass);
        Log.i(TAG, "heightWindowSizeClass : " + heightWindowSizeClass);
    }
}
